<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI角色管理 - 小菊问诊系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.8.0/dist/css/layui.css">
    <script src="https://cdn.jsdelivr.net/npm/layui@2.8.0/dist/layui.js"></script>
    <style>
        .layui-layout-admin .layui-header {
            background-color: rgb(46 125 50 / 90%);
        }
        .layui-layout-admin .layui-side {
            background-color: #393D49;
        }
        .layui-layout-admin .layui-nav-itemed > a {
            background-color: rgb(46 125 50 / 90%) !important;
        }
        .layui-card {
            margin-bottom: 20px;
        }
        .layui-card-header {
            padding: 15px 20px;
            background-color: #f8f8f8;
            border-bottom: 1px solid #eaeaea;
        }
        .layui-card-body {
            padding: 20px;
        }
        .status-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 12px;
        }
        .status-active {
            background-color: #52c41a;
            color: white;
        }
        .status-inactive {
            background-color: #d9d9d9;
            color: #333;
        }
        .role-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        .form-row {
            display: flex;
            gap: 20px;
        }
        .form-col {
            flex: 1;
        }
    </style>
</head>
<body class="layui-layout-body">
    <div class="layui-layout layui-layout-admin">
        <!-- 头部区域 -->
        <div class="layui-header">
            <div class="layui-logo">小菊问诊系统</div>
            <div class="layui-layout-right">
                <ul class="layui-nav layui-layout-right">
                    <li class="layui-nav-item">
                        <a href="javascript:;">
                            <img src="https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=100&q=80" class="layui-nav-img">
                            <span id="admin-username">管理员</span>
                        </a>
                        <dl class="layui-nav-child">
                            <dd><a href="javascript:;" id="logout">退出登录</a></dd>
                        </dl>
                    </li>
                </ul>
            </div>
        </div>
        
        <!-- 侧边栏 -->
        <div class="layui-side layui-bg-black">
            <div class="layui-side-scroll">
                <ul class="layui-nav layui-nav-tree" lay-filter="test">
                    <li class="layui-nav-item">
                        <a href="/admin/">仪表盘</a>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">用户管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="/admin/users">用户列表</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item layui-this">
                        <a href="javascript:;">AI 管理</a>
                        <dl class="layui-nav-child">
                            <dd><a href="/admin/suppliers">供应商管理</a></dd>
                            <dd class="layui-this"><a href="/admin/roles">角色管理</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">问诊记录</a>
                        <dl class="layui-nav-child">
                            <dd><a href="/admin/consultations">问诊列表</a></dd>
                        </dl>
                    </li>
                </ul>
            </div>
        </div>
        
        <!-- 主内容区 -->
        <div class="layui-body">
            <div style="padding: 15px;">
                <div class="layui-card">
                    <div class="layui-card-header">
                        <span>AI 角色管理</span>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="addRole">
                            <i class="layui-icon">&#xe608;</i> 添加角色
                        </button>
                    </div>
                    <div class="layui-card-body">
                        <!-- 数据表格 -->
                        <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
                        
                        <!-- 操作栏模板 -->
                        <script type="text/html" id="roleBar">
                            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
                        </script>
                        
                        <!-- 状态模板 -->
                        <script type="text/html" id="statusTpl">
                            {{#  if(d.is_active){ }}
                            <span class="status-badge status-active">已激活</span>
                            {{#  } else { }}
                            <span class="status-badge status-inactive">已禁用</span>
                            {{#  } }}
                        </script>
                        
                        <!-- 头像模板 -->
                        <script type="text/html" id="avatarTpl">
                            {{#  if(d.avatar){ }}
                            <img src="{{d.avatar}}" class="role-avatar" alt="{{d.name}}">
                            {{#  } else { }}
                            <div class="role-avatar" style="background-color: #1E90FF; color: white; display: flex; align-items: center; justify-content: center; font-size: 18px;">{{d.name.charAt(0)}}</div>
                            {{#  } }}
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 角色编辑弹窗 -->
    <div id="roleEditModal" style="display: none;">
        <form class="layui-form" lay-filter="roleEditForm">
            <input type="hidden" name="role_id">
            <div class="layui-form-item">
                <label class="layui-form-label">角色名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" required lay-verify="required" placeholder="请输入角色名称（如：内科医生、儿科医生等）" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">供应商</label>
                <div class="layui-input-block">
                    <select name="supplier_id" required lay-verify="required" id="supplierSelect">
                        <option value="">请选择AI供应商</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色提示词</label>
                <div class="layui-input-block">
                    <textarea name="prompt" required lay-verify="required" placeholder="请输入角色提示词，描述该AI角色的专业领域、行为准则等" class="layui-textarea" style="height: 200px;"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <textarea name="description" placeholder="请输入角色描述" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">头像URL</label>
                <div class="layui-input-block">
                    <input type="text" name="avatar" placeholder="请输入头像URL（可选）" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="is_active" lay-skin="switch" lay-text="已激活|已禁用" checked>
                </div>
            </div>
        </form>
    </div>
    
    <script>
        layui.use(['jquery', 'layer', 'table', 'form'], function() {
            var $ = layui.jquery;
            var layer = layui.layer;
            var table = layui.table;
            var form = layui.form;
            
            // 退出登录
            $('#logout').click(function() {
                layer.confirm('确定要退出登录吗？', function(index) {
                    $.ajax({
                        url: '/auth/logout',
                        type: 'POST',
                        success: function(res) {
                            if (res.code === 200) {
                                layer.msg('退出成功', {time: 1000}, function() {
                                    window.location.href = '/auth/login';
                                });
                            } else {
                                layer.msg(res.message || '退出失败');
                            }
                        },
                        error: function() {
                            layer.msg('网络错误');
                        }
                    });
                    layer.close(index);
                });
            });
            
            // 获取用户名
            $.ajax({
                url: '/api/user/info',
                type: 'GET',
                success: function(res) {
                    if (res.code === 200) {
                        $('#admin-username').text(res.data.username || '管理员');
                    }
                }
            });
            
            // 加载供应商列表
            function loadSuppliers(selectedId) {
                $.ajax({
                    url: '/admin/api/suppliers',
                    type: 'GET',
                    success: function(res) {
                        if (res.code === 200) {
                            var suppliers = res.data;
                            var select = $('#supplierSelect');
                            select.empty().append('<option value="">请选择AI供应商</option>');
                            
                            suppliers.forEach(function(supplier) {
                                if (supplier.is_active) { // 只显示激活的供应商
                                    var option = $('<option>').val(supplier.id).text(supplier.name);
                                    if (selectedId === supplier.id) {
                                        option.attr('selected', 'selected');
                                    }
                                    select.append(option);
                                }
                            });
                            
                            form.render('select');
                        }
                    }
                });
            }
            
            // 表格渲染
            var roleTable = table.render({
                elem: '#roleTable',
                url: '/admin/api/roles',
                method: 'GET',
                page: false,
                cols: [[
                    {type: 'checkbox'},
                    {field: 'avatar', title: '头像', width: 60, templet: '#avatarTpl'},
                    {field: 'name', title: '角色名称', width: 120},
                    {field: 'supplier_name', title: '供应商', width: 100},
                    {field: 'description', title: '描述', minWidth: 200},
                    {field: 'is_active', title: '状态', width: 80, templet: '#statusTpl'},
                    {field: 'created_at', title: '创建时间', minWidth: 160},
                    {fixed: 'right', title: '操作', toolbar: '#roleBar', width: 120}
                ]],
                response: {
                    statusName: 'code',
                    statusCode: 200,
                    msgName: 'message',
                    dataName: 'data'
                }
            });
            
            // 添加角色
            $('#addRole').click(function() {
                // 清空表单
                form.val('roleEditForm', {
                    'role_id': '',
                    'name': '',
                    'prompt': '',
                    'supplier_id': '',
                    'description': '',
                    'avatar': '',
                    'is_active': 'on'
                });
                
                // 加载供应商列表
                loadSuppliers(null);
                
                // 打开添加弹窗
                layer.open({
                    type: 1,
                    title: '添加AI角色',
                    content: $('#roleEditModal'),
                    area: ['600px', 'auto'],
                    btn: ['确定', '取消'],
                    success: function() {
                        form.render();
                    },
                    yes: function(index) {
                        // 验证表单
                        form.validate();
                        
                        // 获取表单数据
                        var formData = form.val('roleEditForm');
                        
                        // 提交添加
                        $.ajax({
                            url: '/admin/api/roles',
                            type: 'POST',
                            data: {
                                name: formData.name,
                                prompt: formData.prompt,
                                supplier_id: formData.supplier_id,
                                description: formData.description,
                                avatar: formData.avatar,
                                is_active: formData.is_active === 'on'
                            },
                            success: function(res) {
                                if (res.code === 200) {
                                    layer.msg('添加成功', {time: 1000}, function() {
                                        layer.close(index);
                                        roleTable.reload();
                                    });
                                } else {
                                    layer.msg(res.message || '添加失败');
                                }
                            },
                            error: function() {
                                layer.msg('网络错误');
                            }
                        });
                    }
                });
            });
            
            // 监听表格工具事件
            table.on('tool(roleTable)', function(obj) {
                var data = obj.data;
                
                // 编辑角色
                if (obj.event === 'edit') {
                    // 填充表单
                    form.val('roleEditForm', {
                        'role_id': data.id,
                        'name': data.name,
                        'prompt': '', // 需要单独从服务器获取
                        'supplier_id': data.supplier_id,
                        'description': data.description || '',
                        'avatar': data.avatar || '',
                        'is_active': data.is_active ? 'on' : ''
                    });
                    
                    // 加载供应商列表
                    loadSuppliers(data.supplier_id);
                    
                    // 打开编辑弹窗
                    layer.open({
                        type: 1,
                        title: '编辑AI角色',
                        content: $('#roleEditModal'),
                        area: ['600px', 'auto'],
                        btn: ['确定', '取消'],
                        success: function() {
                            // 获取完整的提示词内容（实际应用中需要从服务器获取）
                            $('[name="prompt"]').val('这是一个专业的AI医生角色，专注于回答用户的健康问题...');
                            form.render();
                        },
                        yes: function(index) {
                            // 验证表单
                            form.validate();
                            
                            // 获取表单数据
                            var formData = form.val('roleEditForm');
                            
                            // 提交修改
                            $.ajax({
                                url: '/admin/api/roles/' + formData.role_id,
                                type: 'PUT',
                                data: {
                                    name: formData.name,
                                    prompt: formData.prompt,
                                    supplier_id: formData.supplier_id,
                                    description: formData.description,
                                    avatar: formData.avatar,
                                    is_active: formData.is_active === 'on'
                                },
                                success: function(res) {
                                    if (res.code === 200) {
                                        layer.msg('更新成功', {time: 1000}, function() {
                                            layer.close(index);
                                            roleTable.reload();
                                        });
                                    } else {
                                        layer.msg(res.message || '更新失败');
                                    }
                                },
                                error: function() {
                                    layer.msg('网络错误');
                                }
                            });
                        }
                    });
                }
                
                // 删除角色
                else if (obj.event === 'delete') {
                    layer.confirm('确定要删除该角色吗？', function(index) {
                        $.ajax({
                            url: '/admin/api/roles/' + data.id,
                            type: 'DELETE',
                            success: function(res) {
                                if (res.code === 200) {
                                    obj.del();
                                    layer.msg('删除成功');
                                } else {
                                    layer.msg(res.message || '删除失败');
                                }
                            },
                            error: function() {
                                layer.msg('网络错误');
                            }
                        });
                        layer.close(index);
                    });
                }
            });
        });
    </script>
</body>
</html>